package com.tiny.mirror.service.product.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiny.mirror.basic.common.code.CommonStatusCode;
import com.tiny.mirror.basic.db.domain.Aggregate;
import com.tiny.mirror.basic.db.domain.AggregateFactory;
import com.tiny.mirror.basic.web.exception.BusinessException;
import com.tiny.mirror.service.product.domain.DomainFactory;
import com.tiny.mirror.service.product.domain.ability.Ability;
import com.tiny.mirror.service.product.domain.ability.repository.AbilityRepository;
import com.tiny.mirror.service.product.infrastructure.entity.db.AbilityEntity;
import com.tiny.mirror.service.product.infrastructure.repository.db.AbilityMapper;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Repository;

/**
 * @author: chenhao
 * @description:
 * @date: 2023/8/28
 **/
@Repository
public class AbilityRepositoryImpl implements AbilityRepository {

  @Resource
  private AbilityMapper abilityMapper;

  @Override
  public Aggregate<Ability> findById(long id) {
    Ability ability = findAbilityById(id);
    return AggregateFactory.createAggregate(ability);
  }

  @Override
  public Ability findAbilityById(long id) {
    AbilityEntity entity = abilityMapper.selectById(id);
    if (Objects.isNull(entity)) {
      throw new BusinessException(CommonStatusCode.DATA_NOT_EXIST.args("app:" + id));
    }
    return DomainFactory.convertToAbility(entity);
  }

  @Override
  public List<Ability> findAbilityByIds(List<Long> ids) {
    QueryWrapper<AbilityEntity> queryWrapper = new QueryWrapper<>();
    queryWrapper.lambda().in(AbilityEntity::getId, ids);
    List<AbilityEntity> list = abilityMapper.selectList(queryWrapper);
    if (CollectionUtils.isEmpty(list)) {
      return Collections.emptyList();
    }
    return list.stream().map(l -> DomainFactory.convertToAbility(l)).collect(Collectors.toList());
  }
}
